#!/usr/bin/env python2

# Copyright (c) 2018 makerdiary
# All rights reserved.
# 
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are
# met:
#
# * Redistributions of source code must retain the above copyright
#   notice, this list of conditions and the following disclaimer.
#
# * Redistributions in binary form must reproduce the above
#   copyright notice, this list of conditions and the following
#   disclaimer in the documentation and/or other materials provided
#   with the distribution.

# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
# "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
# A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
# OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
# SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
# LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
# DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
# THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
# (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.

import time
from sys import argv
import os
import sys
import re
import random

argv.pop(0)
if len(sys.argv) != 2:
    print("No input key & certificate files!")
    print('Usage: python der2array.py <ec.key> <certificate.der>')
    sys.exit()

print("Converting EC key to text...")

ret = os.system("openssl ec -in " + argv[0] + " -text -out tmp.key")
if ret != 0:
    print("Error converting EC key: " + argv[0])
    sys.exit(1)

f_key = open('tmp.key')

key = f_key.read()

tmpkeys = re.findall(r'\b(?:[0-9a-f]{2})+\b', key, re.S)

index = 0

result = "/* This file was automatically generated by cert2array.py at " + time.ctime() + " */\n"
result += '\n#include <stdint.h>\n'

result += '\nconst uint8_t attestation_private_key[] = {\n    '

if tmpkeys[0] == '00':
    tmpkeys.pop(0)

for x in tmpkeys:
    if index < 32:
        result += '0x' + x + ', '
        index += 1
        if index == 16:
            result += '\n    '
    else:
        break;

result += '\n};\n\n'

result += 'uint8_t attestation_private_key_size = sizeof(attestation_private_key);\n\n'

f_key.close();


f_cert = open(argv[1], 'rb')
f_cert.seek(0,0) 
index=0
result += 'const uint8_t attestation_cert[] = {\n    '

while True:  
    temp=f_cert.read(1)  
    if len(temp) == 0:  
        break  
    else:
    	result += '0x' + temp.encode('hex') + ', '
        index += 1  
    if index == 16:  
        index=0  
        result += '\n    '   
f_cert.close()
result += '\n};\n\n'

result += 'uint16_t attestation_cert_size = sizeof(attestation_cert);\n\n'

result += 'uint8_t aes_key[] = {\n    '

for i in range(16):
    result += hex(random.randint(0, 255)) + ', '

result += '\n};\n\n'

# Write to output file so we can use it
with open('keys.c', 'w') as output_f:
    output_f.write(result)

# Delete tmp.raw
ret = os.system('rm tmp.key')
if ret != 0:
    print("Error delete tmp.key.")
    sys.exit(1)

print('Successfully Completed!')
print('The private key and certificate are stored in certs/keys.c')
print('Bye bye~')